package com.mawujun.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mawujun.util.Encrypt;
import com.mawujun.util.State;
import com.mawujun.util.StateCache;
import com.mawujun.util.User;

@Controller
public class LogonController {
	@Autowired
	private JdbcTemplate jdbcTemplate1;
	//http://blog.csdn.net/pengrg166/archive/2006/12/29/1467607.aspx



	@RequestMapping("/logon.do")
	public void logon(HttpServletRequest request,HttpServletResponse response,User user, Writer writer) throws IOException{
		
		 //判断用户是否已经登录
  	  HashMap<String,Integer> online=(HashMap)request.getSession().getServletContext().getAttribute("onLineUser");
  	  if(online!=null&&online.get(user.getId())!=null){
  		writer.write("{success:false,errors:{msg:'用戶已登录！'}}");
  		writer.close();
  		  return;
  	  }
  	  
		//帐套AccInformation
		//用户表UA_USER
		if(user.getPassword()==null){
			user.setPassword("");
		}
		Encrypt en=new Encrypt();
		String password=en.getBASE64(en.SHA1ToHax(user.getPassword()))+"";//用户名1:。密码:NWoZK3kTsExUV00Ywo1G5jlUKKs=
		String sql="select distinct cUser_Name from UA_USER where cUser_Id='"+user.getId()+"' and cPassword='"+password+"'";
//		int size=jdbcTemplate1.queryForInt(sql);
//		if(size<=0){
//     	    writer.write("{success:false,errors:{msg:'用户名或密码错误，请重新输入！'}}");
//    		writer.close();
//     	    return;
//		}
		List<Map<String,Object>> list=jdbcTemplate1.queryForList(sql);
		if(list==null || list.size()==0){
			 writer.write("{success:false,errors:{msg:'用户名或密码错误，请重新输入！'}}");
	    	 writer.close();
	     	 return;
		}
		for(Map<String,Object> map:list){
			user.setName(map.get("cUser_Name")+"");
		}
		
		request.getSession().setAttribute("user", user);
		writer.write("{success:true}");
 		writer.close();
		
	}
	
	@RequestMapping("/findZhangt.do")
	public void findZhangt(HttpServletRequest request, Writer writer) throws IOException{
		String sql="select distinct cAcc_Id,cAcc_Name from UA_Account";
		List<Map<String,Object>> list=jdbcTemplate1.queryForList(sql);
		
		JSONArray jsonItems = new JSONArray();
		for(Map<String,Object> map:list){
			JSONArray jsonObject = new JSONArray();
			jsonObject.add(map.get("cAcc_Id"));
			jsonObject.add("["+map.get("cAcc_Id")+"]"+map.get("cAcc_Name"));
			jsonItems.add(jsonObject);
		}
		writer.write(jsonItems.toString());
 		writer.close();
		
	}
	
	@RequestMapping("/logout.do")
	public void logout(HttpServletRequest request, Writer writer) throws IOException{
		
		request.getSession().setAttribute("user", null);
		request.getSession().invalidate();
		writer.write("{success:true}");
 		writer.close();
		
	}
	
	/**
	 * 获取用户在某个模块上的状态，是导入完成还是么有导入
	 * 状态 0，表示要导入，1正在导入，2导入完成,导到测试库的表里面了，要是没有记录表示要导入和0的状态一样
	 * @param request
	 * @param model
	 * @param writer
	 * @throws IOException 
	 */
	@RequestMapping("/getState.do")
	public void getState(HttpServletRequest request,String model, Writer writer) throws IOException {
		User user=(User)request.getSession().getAttribute("user");
		String state="{state:0}";
		
		String key=user.getName()+user.getDbName()+model;
		if(StateCache.getState(key)!=null){
			//state="{state:"+StateCache.getState(key).+"}";
			JSONObject state1=JSONObject.fromObject(StateCache.getState(key));
			writer.write(state1.toString());
	 		writer.close();
	 		return;
		}
		
		//获取用户的导入状态
		String sql="select * from UA_excelToDb_IS where cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'";
		List<Map<String,Object>> list=jdbcTemplate1.queryForList(sql);
		
		for(Map<String,Object> map:list){
			state="{state:"+map.get("state")+"}";
		}
		writer.write(state);
 		writer.close();
	}
	
	public void setState(User user, String model,int state){
		if(model==null){
			throw new IllegalArgumentException("model参数不能为空。");
		}
		
		String key=user.getName()+user.getDbName()+model;
		if(state==4){
			jdbcTemplate1.execute("delete UA_excelToDb_IS where  cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'");
			StateCache.removeState(key);
			return;
		}
		StateCache.addState(key, state);
		
		String sql="delete UA_excelToDb_IS where cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'";
		String insert="insert into UA_excelToDb_IS values('"+user.getName()+"','"+user.getDbName()+"','"+model+"','"+state+"')";
		jdbcTemplate1.batchUpdate(new String[]{sql,insert});
	}
	
	public void setState(User user, String model,int state,String msg){
		if(model==null){
			throw new IllegalArgumentException("model参数不能为空。");
		}
		
		if(getState(user, model)!=null){
			getState(user, model).setMsg(msg);
			if(getState(user, model).getState()==state){
				return;//如果状态已经
			} else if(state==3){//如果发生异常，不更新到数据库
				getState(user, model).setState(state);
				return;
			}
		}
		
		String sql="delete UA_excelToDb_IS where cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'";
		String insert="insert into UA_excelToDb_IS values('"+user.getName()+"','"+user.getDbName()+"','"+model+"','"+state+"')";
		jdbcTemplate1.batchUpdate(new String[]{sql,insert});
	}
	
	public void setState(User user, String model,int state,double schedule ,String msg){
		if(model==null){
			throw new IllegalArgumentException("model参数不能为空。");
		}
		
		if(getState(user, model)!=null){
			getState(user, model).setMsg(msg);
			getState(user, model).setSchedule(schedule);
			if(getState(user, model).getState()==state){
				return;//如果状态已经
			}
		}
		
		String sql="delete UA_excelToDb_IS where cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'";
		String insert="insert into UA_excelToDb_IS values('"+user.getName()+"','"+user.getDbName()+"','"+model+"','"+state+"')";
		jdbcTemplate1.batchUpdate(new String[]{sql,insert});
	}
	
	
	private State getState(User user, String model){
		String key=user.getName()+user.getDbName()+model;
		if(StateCache.getState(key)!=null){
			return StateCache.getState(key);
		}
		//获取用户的导入状态
		String sql="select * from UA_excelToDb_IS where cUser_Name='"+user.getName()+"' and DbName='"+user.getDbName()+"' and model='"+model+"'";
		State state=null;
		try {
			state=jdbcTemplate1.queryForObject(sql, State.class);
		} catch(Exception e) {
			e.printStackTrace();
			
		}
		
		return state;
		
	}
//	public void setState(User user, String model,State state){
//		setState(user,  model, state.getState());
//		
//	}

	public JdbcTemplate getTemplate() {
		return jdbcTemplate1;
	}

	public void setTemplate(JdbcTemplate template) {
		this.jdbcTemplate1 = template;
	}
}
